package com.zs.backend.modules.mobileManagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zs.backend.common.UserHolder;
import com.zs.backend.common.utils.BeanUtil;
import com.zs.backend.common.utils.CollectionUtil;
import com.zs.backend.common.utils.ExcelParser;
import com.zs.backend.common.utils.StringUtil;
import com.zs.backend.modules.mobileManagement.dto.MobileManagementDTO;
import com.zs.backend.modules.mobileManagement.dto.MobileManagementExcelDTO;
import com.zs.backend.modules.mobileManagement.model.MobileManagement;
import com.zs.backend.modules.mobileManagement.mapper.MobileManagementMapper;
import com.zs.backend.modules.mobileManagement.service.MobileManagementService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zs.backend.modules.ums.dto.UserDTO;
import com.zs.backend.modules.ums.model.UmsAdmin;
import com.zs.backend.modules.ums.model.UmsRole;
import com.zs.backend.modules.userQueryPwd.model.UserQueryPwd;
import com.zs.backend.modules.userQueryPwd.service.UserQueryPwdService;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 手机管理表 服务实现类
 * </p>
 *
 * @author zs
 * @since 2024-03-18
 */
@Service
public class MobileManagementServiceImpl extends
    ServiceImpl<MobileManagementMapper, MobileManagement> implements MobileManagementService {

    @Autowired
    @Qualifier("mobileManagementThreadPool")
    private ExecutorService executorService;

    @Autowired
    private UserQueryPwdService userQueryPwdService;

//    private static ThreadLocal<UmsAdmin> currentUser = new ThreadLocal<>();

    @Override
    public Page<MobileManagementDTO> list(MobileManagementDTO dto, Integer pageSize, Integer pageNum) {
        Page<MobileManagement> page = new Page<>(pageNum,pageSize);
        QueryWrapper<MobileManagement> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<MobileManagement> lambda = wrapper.lambda();
        lambda.like(StringUtil.isNotEmpty(dto.getArea()),
            MobileManagement::getArea, dto.getArea());
        lambda.like(StringUtil.isNotEmpty(dto.getManagementUser()),
            MobileManagement::getManagementUser, dto.getManagementUser());

        lambda.ge(dto.getStartYearTime() != null,
            MobileManagement::getYearTime, dto.getStartYearTime());
        lambda.le(dto.getEndYearTime() != null,
            MobileManagement::getYearTime, dto.getEndYearTime());

        lambda.ge(dto.getStartCallTime() != null,
            MobileManagement::getCallTime, dto.getStartCallTime());
        lambda.le(dto.getEndCallTime() != null,
            MobileManagement::getCallTime, dto.getEndCallTime());

        lambda.like(StringUtil.isNotEmpty(dto.getIdCard()),
            MobileManagement::getIdCard, dto.getIdCard());

        lambda.like(StringUtil.isNotEmpty(dto.getCertificateNumber()),
            MobileManagement::getCertificateNumber, dto.getCertificateNumber());

        lambda.like(StringUtil.isNotEmpty(dto.getMajor()),
            MobileManagement::getMajor, dto.getMajor());

        lambda.like(dto.getStatus() != null,
            MobileManagement::getStatus, dto.getStatus());

        lambda.like(StringUtil.isNotEmpty(dto.getTel()),
            MobileManagement::getTel, dto.getTel());
        lambda.like(StringUtil.isNotEmpty(dto.getTitleCategory()),
            MobileManagement::getTitleCategory, dto.getTitleCategory());

        lambda.eq(StringUtil.isNotEmpty(dto.getAreaCode()),
            MobileManagement::getAreaCode, dto.getAreaCode());

        lambda.orderByDesc(MobileManagement::getUpdateTime);

        UserDTO userDTO = UserHolder.getCurrentAdmins();
        if(userDTO != null && CollectionUtil.isNotNullAndEmpty(userDTO.getUmsRoleList())){
            List<String> roleList = userDTO.getUmsRoleList().stream().map(UmsRole::getName).collect(Collectors.toList());
            if(!roleList.contains("超级管理员")){
                lambda.eq(MobileManagement::getStatus, 0);
            }
        }
        Page<MobileManagement> pageList = page(page,wrapper);
        if(pageList == null){
            return new Page<>();
        }
        List<MobileManagementDTO> result = BeanUtil.beanCopyPropertiesForList(pageList.getRecords(), MobileManagementDTO.class);
        if(CollectionUtil.isNotNullAndEmpty(result)){

            for(MobileManagementDTO mobileManagementDTO : result){
                if(StringUtil.isNotEmpty(mobileManagementDTO.getTel())){
                    mobileManagementDTO.setEncodeTel(StringUtil.encryptPhoneNumber(mobileManagementDTO.getTel()));
                }
                if(StringUtil.isNotEmpty(mobileManagementDTO.getIdCard())){
                    mobileManagementDTO.setEncodeIdCard(StringUtil.encryptIdCardNumber(mobileManagementDTO.getIdCard()));
                }
            }
        }
        Page<MobileManagementDTO> pageResult = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        pageResult.setRecords(result);
        return pageResult;
    }

    @Override
    public boolean addOrUpt(MobileManagementDTO request) {
        UmsAdmin umsAdmin = UserHolder.getCurrentAdmin();
        request.setCreateUid(umsAdmin.getId());
        request.setCreateUname(umsAdmin.getUsername());

        MobileManagement mobileManagement = BeanUtil.beanCopyProperties(request, MobileManagement.class);

        if(request.getId() != null){
            return updateById(mobileManagement);
        }
        return save(mobileManagement);
    }

    @Override
    public boolean uploadExcel(MultipartFile file) {
        // 假设当前登录人信息存储在ThreadLocal中
        // 设置当前登录人信息
//        currentUser.set(UserHolder.getCurrentAdmin());
//        UmsAdmin umsAdmin = currentUser.get();
        System.out.println("开始时间：" + System.currentTimeMillis());
        List<MobileManagementExcelDTO> mobileManagementDTOList = ExcelParser.parseExcelFile(file, MobileManagementExcelDTO.class);
        System.out.println("解析结束时间：" + System.currentTimeMillis());
        executorService.execute(() -> {
            List<MobileManagement> mobileManagements = BeanUtil.beanCopyPropertiesForList(mobileManagementDTOList, MobileManagement.class);
            saveBatch(mobileManagements);
            System.out.println("导入结束时间：" + System.currentTimeMillis());
        });


        // 异步执行
//        executorService.execute(() -> {
//            try {
//                // 从ThreadLocal中获取当前登录人信息 umsAdmin
//
//                List<MobileManagementExcelDTO> mobileManagementDTOList = ExcelParser.parseExcelFile(file, MobileManagementExcelDTO.class);
//                List<MobileManagement> mobileManagements = BeanUtil.beanCopyPropertiesForList(mobileManagementDTOList, MobileManagement.class);
//                saveBatch(mobileManagements);
//            }catch (Exception e){
//                e.printStackTrace();
//            }finally {
//                // 清理ThreadLocal数据
//                currentUser.remove();
//            }
//        });

        return true;
    }

    @Override
    public boolean checkPwd(String pwd) {
        // 查询查看密码
        QueryWrapper<UserQueryPwd> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<UserQueryPwd> lambda = wrapper.lambda();
        lambda.eq(UserQueryPwd::getType, 1);
        UserQueryPwd userQueryPwd = userQueryPwdService.getOne(wrapper);
        if(userQueryPwd == null){
            return false;
        }
        String password = userQueryPwd.getPwd();
        if(pwd.equals(password)){
            return true;
        }
        return false;
    }

    @Override
    public boolean setPwd(String pwd) {
        UserQueryPwd userQueryPwd = new UserQueryPwd();
        userQueryPwd.setPwd(pwd);
        userQueryPwdService.save(userQueryPwd);
        return true;
    }

    @Override
    public boolean checkPwd(String pwd, Integer type) {
        // 查询查看密码
        QueryWrapper<UserQueryPwd> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<UserQueryPwd> lambda = wrapper.lambda();
        lambda.eq(UserQueryPwd::getType, type);
        UserQueryPwd userQueryPwd = userQueryPwdService.getOne(wrapper);
        if(userQueryPwd == null){
            return false;
        }
        String password = userQueryPwd.getPwd();
        if(pwd.equals(password)){
            return true;
        }
        return false;
    }

    @Override
    public boolean setPwd(String pwd, Integer type) {
        UserQueryPwd userQueryPwd = new UserQueryPwd();
        userQueryPwd.setPwd(pwd);
        userQueryPwd.setType(type);
        userQueryPwdService.save(userQueryPwd);
        return true;
    }


}
